package com.dm.action;

import com.dm.common.Const;
import com.dm.dto.ResponseDto;
import com.dm.dto.input.UserDto;
import com.dm.service.UserService;
import com.dm.utils.JsonRequestDataUtil;
import com.opensymphony.xwork2.ActionSupport;
import lombok.Data;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author hqw521@qq.com
 * @date 2018/11/14 23:21
 */
@Data
@Namespace("/dm/user")
@ParentPackage("json-default")
@Results({@Result(name = "jsonData", type = "json", params = {"root", "jsonData"})})
public class UserAction extends ActionSupport {
    private String jsonData;

    @Autowired
    private UserService userService;

    @Action("login")
    public String login() {
        UserDto userDto = (UserDto) JsonRequestDataUtil.getBean(ServletActionContext.getRequest(), UserDto.class);
        ResponseDto<UserDto> responseDto = userService.login(userDto);
        this.jsonData = JSONObject.fromObject(responseDto).toString();
        return Const.JSON;
    }

    @Action("register")
    public String register() {
        UserDto userDto = (UserDto) JsonRequestDataUtil.getBean(ServletActionContext.getRequest(), UserDto.class);
        ResponseDto responseDto = userService.register(userDto);
        this.jsonData = JSONObject.fromObject(responseDto).toString();
        return Const.JSON;
    }

    @Action("findAllUser")
    public String findAllUser() {
        ResponseDto<List<UserDto>> responseDto = userService.findAllUser();
        this.jsonData = JSONObject.fromObject(responseDto).toString();
        return Const.JSON;
    }
}
